const socket = io();
const currentUserId = localStorage.getItem('userId');
const currentNickname = localStorage.getItem('nickname');
if (!currentUserId) {
  console.error('用户未登录，无法加载聊天界面');
  window.location.href = 'index.html'; // 重定向到登录页
} else {
  // 发送上线事件,让服务器将 socket 加入对应房间
  socket.emit('online', {
    userId: currentUserId,
    nickname: currentNickname
  });
}

document.addEventListener('DOMContentLoaded', () => {
  const htmlEl = document.documentElement;
  const gradientBtn = document.getElementById('gradientToggle');

  // 预设渐变 & “随机” 标记
  const presets = [
    'linear-gradient(135deg, #ff6a88 0%, #85fbd0 100%)',
    'linear-gradient(135deg, #AEE6E6 0%, #F6F8D4 100%)',
    'linear-gradient(to right, rgb(18, 194, 233), rgb(196, 113, 237), rgb(246, 79, 89))',
    'linear-gradient(to right, rgb(198, 255, 221), rgb(251, 215, 134), rgb(247, 121, 125))',
    'linear-gradient(to right, #6B8857, #A7C190, #FAF2CB, #FFFFFF)',
    'linear-gradient(to right, #795F9C, #B484B0, #EEDACA, #F0D8F0, #FFFFFF)',
    'linear-gradient(to right, #886441, #FEC187, #EDCBB9, #EAD9C8, #FFFFFF)',
    'linear-gradient(to right, #518463, #A6D3B1, #CCF2E0, #EED8F6, #FFFFFF)',
    'linear-gradient(to right, #D85B72, #ECAEB9, #EFEEC6, #F4796A, #FFFFFF)',
    'random'
  ];
  let idx = 0;

  function genRandomColor() {
    // 生成如 #A1B2C3 的随机颜色
    return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
  }

  function applyGradient(str) {
    const gradient = str === 'random'
      ? `linear-gradient(135deg, ${genRandomColor()}, ${genRandomColor()})`
      : str;
    // 更新 CSS 变量
    htmlEl.style.setProperty('--gradient-pink-blue', gradient);
    // 如果 #backgroundCanvas 也用了写死的 background，需要同步更新它：
    const bgDiv = document.getElementById('backgroundCanvas');
    if (bgDiv) bgDiv.style.background = gradient;
  }

  gradientBtn && gradientBtn.addEventListener('click', () => {
    applyGradient(presets[idx]);
    idx = (idx + 1) % presets.length;
  });
  // 1. 暗/亮模式切换
  const toggle = document.getElementById('modeToggle');
  if (toggle) {
    toggle.addEventListener('click', () => {
      const html     = document.documentElement;
      const newTheme = html.dataset.theme === 'dark' ? 'light' : 'dark';
      html.dataset.theme = newTheme;
      toggle.querySelector('i').className =
        newTheme === 'dark' ? 'bx bxs-sun' : 'bx bx-moon';
    });
  }

  function isMobileDevice() {
    return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  }

  // 2. 粒子背景（particles.js）
  if (window.particlesJS) { // !isMobileDevice() && 
    particlesJS('backgroundCanvas', {
      particles: {
        number: { value: 50 },
        size:   { value: 3 },
        line_linked: { enable: true, distance: 120, color: '#888', opacity: 0.3 },
        move: { speed: 1 }
      }
    });
  }

  // 3. 头像编辑弹窗
  const uploadButton = document.getElementById('uploadButton');
  const fileInput = document.getElementById('modalAvatarInput');
  const modalPreview = document.getElementById('modalAvatarPreview');
  const avatarModal = document.getElementById('avatarModal');
  const editIcon = document.querySelector('.edit-icon');
  const modalClose = document.querySelector('.modal-close');
  const modalCancel = document.getElementById('modalCancel');
  const modalSave = document.getElementById('modalSave');
  const avatarPreview = document.getElementById('avatarPreview');
  const avatarInput = document.getElementById('avatarUrl');

  uploadButton.addEventListener('click', () => {
    fileInput.click();
  });

  fileInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    // Validate file type and size
    if (!file.type.startsWith('image/')) {
      showToast('请选择图片文件', 'error');
      return;
    }
    if (file.size > 5 * 1024 * 1024) { // 5MB limit
      showToast('图片大小不能超过5MB', 'error');
      return;
    }

    try {
      // Create FormData
      const formData = new FormData();
      formData.append('image', file);
      
      // Upload image
      const response = await axios.post('/api/upload/image', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      // Update preview and input value
      const imagePath = response.data.path; // Should be like '/upload/images/filename.jpg'
      modalPreview.src = imagePath;
      avatarInput.value = imagePath;
      
      showToast('图片上传成功', 'success');
    } catch (err) {
      showToast('图片上传失败: ' + (err.response?.data?.message || err.message), 'error');
      console.error(err);
    }
  });

  // 打开模态框
  editIcon.addEventListener('click', () => {
    avatarModal.style.display = 'block';
    modalPreview.src = avatarPreview.src;
  });

  // 关闭模态框的几种方式
  function closeModal() {
    const modal = document.getElementById('avatarModal');
    if (modal) {
      modal.style.display = 'none';
    }
  }

  modalClose.addEventListener('click', closeModal);
  modalCancel.addEventListener('click', closeModal);
  
  // 点击模态框外部关闭
  window.addEventListener('click', (e) => {
    if (e.target === avatarModal) {
      closeModal();
    }
  });

  // 4. 主表单、密码表单、Toast 容器
  const infoForm      = document.getElementById('infoForm');
  const passwordForm  = document.getElementById('passwordForm');
  const toastContainer= document.getElementById('toastContainer');
  const backBtn       = document.getElementById('backButton');

  // 回退按钮
  backBtn && backBtn.addEventListener('click', () => history.back());

  // Toast 通知函数
  function showToast(text, type = 'info') {
    const container = document.getElementById('toastContainer');
    if (!container) return;

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = text;
    container.appendChild(toast);

    // Remove toast after animation
    setTimeout(() => toast.remove(), 3000);
  }

  // 获取并填充个人信息
  async function loadProfile() {
    try {
      const userId = localStorage.getItem('userId');
      const response = await axios.get(`/api/user/profile/${userId}`);
      const user = response.data;
      
      document.getElementById('userId').value = user.userId || '';
      document.getElementById('nickname').value = user.nickname || '';
      document.getElementById('email').value = user.email || '';
      
      // 设置性别选中状态
      if (user.gender) {
        const genderRadio = document.querySelector(`input[name="gender"][value="${user.gender}"]`);
        if (genderRadio) {
          genderRadio.checked = true;
        }
      }
      
      document.getElementById('bio').value = user.bio || '';
      
      // 更新字符计数
      const bioCounter = document.getElementById('bioCount');
      if (bioCounter) {
        bioCounter.textContent = (user.bio || '').length;
      }
      
      if (user.avatar) {
        document.getElementById('avatarPreview').src = user.avatar;
        avatarInput.value = user.avatar;
      }
    } catch (err) {
      console.error('加载个人信息失败:', err);
      showToast('加载失败，请刷新页面重试', 'error');
    }
  }

  // 实时预览头像 URL
  avatarInput && avatarInput.addEventListener('input', () => {
    avatarPreview.src = avatarInput.value || avatarPreview.src;
  });

  // 提交基本信息
  infoForm && infoForm.addEventListener('submit', async e => {
    e.preventDefault();
    try {
      // 获取选中的性别值
      const selectedGender = document.querySelector('input[name="gender"]:checked');
      
      const payload = {
        userId:   document.getElementById('userId').value,
        nickname: document.getElementById('nickname').value.trim(),
        email:    document.getElementById('email').value.trim(),
        gender:   selectedGender ? selectedGender.value : '', // 使用正确的方式获取性别
        bio:      document.getElementById('bio').value, // 注意：应该是 .value 而不是 .content
        avatar:   avatarInput.value.trim()
      };
      await axios.put('/api/user/profile', payload);
      localStorage.setItem('nickname', payload.nickname);
      localStorage.setItem('avatar', payload.avatar);
      showToast('个人信息更新成功', 'success');
    } catch (err) {
      showToast('更新失败：' + (err.response?.data?.message || err.message), 'error');
      console.error(err);
    }
  });

  // 提交密码修改
  passwordForm && passwordForm.addEventListener('submit', async e => {
    e.preventDefault();
    const oldPwd     = document.getElementById('oldPassword').value;
    const newPwd     = document.getElementById('newPassword').value;
    const confirmPwd = document.getElementById('confirmPassword').value;
    if (newPwd !== confirmPwd) {
      showToast('两次密码输入不一致', 'error');
      return;
    }

    const oldPwdHash = CryptoJS.SHA256(oldPwd).toString();
    const newPwdHash = CryptoJS.SHA256(newPwd).toString();
    try {
      await axios.put('/api/user/password', {
        userId:      localStorage.getItem('userId'),
        oldPassword: oldPwdHash,
        newPassword: newPwdHash
      });
      passwordForm.reset();
      showToast('密码更新成功，请重新登录', 'success');
      setTimeout(() => {
        localStorage.clear();
        location.replace('index.html');
      }, 1500);
    } catch (err) {
      showToast('更新密码失败：' + (err.response?.data?.message || err.message), 'error');
      console.error(err);
    }
  });

  // Modify the modalSave click handler
  modalSave.addEventListener('click', async () => {
    try {
      const newAvatarPath = modalPreview.src;
      
      const response = await axios.put('/api/user/profile', {
        userId: currentUserId,
        avatar: newAvatarPath
      });

      if (response.data.success) {
        // Update local storage
        localStorage.setItem('avatar', newAvatarPath);
        
        // Update both preview images
        const mainAvatar = document.getElementById('avatarPreview');
        if (mainAvatar) {
          // Force reload by adding timestamp
          mainAvatar.src = newAvatarPath + '?t=' + new Date().getTime();
        }
        
        // Also update the hidden input if it exists
        const avatarUrlInput = document.getElementById('avatarUrl');
        if (avatarUrlInput) {
          avatarUrlInput.value = newAvatarPath;
        }
        
        // Close modal
        closeModal();
        
        // Show success toast
        showToast('头像更新成功', 'success');
      }
    } catch (err) {
      showToast('保存失败: ' + (err.response?.data?.message || err.message), 'error');
      console.error('保存头像失败:', err);
    }
  });

  // 在加载用户信息时添加新字段
  async function loadUserInfo() {
    try {
      const userId = localStorage.getItem('userId');
      const response = await axios.get(`/api/user/${userId}`);
      const user = response.data;
      
      document.getElementById('userId').value = user.userId;
      document.getElementById('nickname').value = user.nickname;
      document.getElementById('email').value = user.email;
      document.getElementById('gender').value = user.gender || '其他';
      document.getElementById('bio').value = user.bio || '';
      
      // 设置头像预览
      const avatarPreview = document.getElementById('avatarPreview');
      avatarPreview.src = user.avatar;
    } catch (error) {
      console.error('加载用户信息失败:', error);
      showToast('加载用户信息失败', 'error');
    }
  }

  // 在profile.js中添加
  const bioTextarea = document.getElementById('bio');
  const bioCounter = document.getElementById('bioCount');

  bioTextarea.addEventListener('input', function() {
    const count = this.value.length;
    bioCounter.textContent = count;
    
    const counterElement = bioCounter.parentElement;
    counterElement.classList.remove('warning', 'danger');
    
    if (count > 180) {
      counterElement.classList.add('danger');
    } else if (count > 150) {
      counterElement.classList.add('warning');
    }
  });

  loadProfile();
});

// 1908811070